package linkedlist.leetcode_19;

public class NoExtraNode {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        while (n != 0) {
            fast = fast.next;
            n--;
        }
        // 如果 fast 走完 n 步后为 Null，说明删除的是头节点，此时直接返回 head.next
        if (fast == null) {
            return head.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
